package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"user-h2/api/request"
	"user-h2/api/responres"
	"user-h2/dao"
	"user-h2/models"
	"user-h2/pkg"
	"user-h2/util"
)

func Register(c *gin.Context) {
	var data request.Register
	if err := c.ShouldBind(&data); err != nil {
		responres.ResPonresDataError(c, err.Error())
		return
	}
	user, err := dao.GetUser(data.Phone)
	if err != nil {
		responres.ResPonresDataError(c, "查询失败")
		return
	}
	if user.Phone != "" {
		responres.ResPonresDataError(c, "用户已注册")
		return
	}
	users := models.User{
		Phone:    data.Phone,
		Password: util.PwdMd5(data.Password),
	}
	err = dao.Create(&users)
	if err != nil {
		responres.ResPonresDataError(c, "添加失败")
		return
	}
	responres.ResPonresDataSuccess(c, users.ID)

}

func Login(c *gin.Context) {
	var data request.Register
	if err := c.ShouldBind(&data); err != nil {
		responres.ResPonresDataError(c, err.Error())
		return
	}
	user, err := dao.GetUser(data.Phone)
	if err != nil {
		responres.ResPonresDataError(c, "查询失败")
		return
	}
	if user.Phone == "" {
		responres.ResPonresDataError(c, "用户未注册")
		return
	}
	if util.PwdMd5(data.Password) != user.Password {
		responres.ResPonresDataError(c, "密码错误")
		return
	}
	token, err := pkg.GetJwtToken(strconv.Itoa(int(user.ID)))
	if err != nil {
		responres.ResPonresDataError(c, "token连接失败")
		return
	}
	responres.ResPonresDataSuccess(c, token)
}
